const config = require('../config');

const winston = require('winston');
const DailyRotateFile = require('winston-daily-rotate-file');
const path = require('path');
const moment = require('moment-timezone');

const dateFormat = function () {
  return moment().tz('Asia/Shanghai').format('YYYY-MM-DD HH:mm:ss:SSS');
}

const mkdir = function (str) {
  const fileUri = config.app.name + '-' + config.app.port + '-' + str;
  return path.resolve(config.log.dir, str);
}

const consoleTransport = new (winston.transports.Console)({
  timeStamp: dateFormat,
  level: 'debug',
  colorize: false,
  prettyPrint: true
})

const allLoggerTransport = new DailyRotateFile({
  name: 'all',
  filename: mkdir('all.log'),
  timestamp: dateFormat,
  level: 'debug',
  colorize: false,
  prettyPrint: true,
  maxsize: 1024 * 1024 * 10,
  datePattern: '.yyy-MM-dd'
})

const errorTransport = new (winston.transports.File)({
  name: 'error',
  filename: mkdir('error.log'),
  timestamp: dateFormat,
  level: 'error',
  prettyPrint: true,
  colorize: false
})

const Transport = [consoleTransport];

if (config.app.logFile) {
  Transport.push(allLoggerTransport);
  Transport.push(errorTransport);
}

exports.logger = new (winston.Logger)({
  transports: Transport
});
